package com.tourism.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tourism.common.Result;
import com.tourism.entity.User;
import com.tourism.mapper.UserMapper;
import com.tourism.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;  // 添加这个

    @Override
    public Result login(String username, String password) {
        try {
            // 1. 根据用户名查询用户
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, username);
            User user = getOne(queryWrapper);

            // 2. 检查用户是否存在
            if (user == null) {
                return Result.fail("用户不存在");
            }

            // 3. 使用 BCrypt 验证密码
            if (!passwordEncoder.matches(password, user.getPassword())) {
                return Result.fail("密码错误");
            }
            // 4. 登录成功，清除密码后返回用户信息
            user.setPassword(null);
            return Result.success(user);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("登录失败：" + e.getMessage());
        }
    }
    @Override
    public Result getUserList(Integer page, Integer pageSize, String username, String phone) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        // 添加搜索条件
        if (StringUtils.hasText(username)) {
            queryWrapper.like(User::getUsername, username);
        }
        if (StringUtils.hasText(phone)) {
            queryWrapper.like(User::getPhone, phone);
        }

        // 分页查询
        IPage<User> pageResult = new Page<>(page, pageSize);
        page(pageResult, queryWrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("list", pageResult.getRecords());
        data.put("total", pageResult.getTotal());

        return Result.success(data);
    }

    @Override
    public Result addUser(User user) {
        // 检查用户名是否已存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        if (count(queryWrapper) > 0) {
            return Result.fail("用户名已存在");
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 保存用户
        if (save(user)) {
            return Result.success("添加用户成功");
        }
        return Result.fail("添加用户失败");
    }

    @Override
    public Result updateUser(User user) {
        // 检查用户是否存在
        User existingUser = getById(user.getId());
        if (existingUser == null) {
            return Result.fail("用户不存在");
        }

        // 如果修改了用户名，检查新用户名是否已存在
        if (!existingUser.getUsername().equals(user.getUsername())) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, user.getUsername());
            if (count(queryWrapper) > 0) {
                return Result.fail("用户名已存在");
            }
        }

        // 如果密码为空，保持原密码不变
        if (StringUtils.hasText(user.getPassword())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        } else {
            user.setPassword(existingUser.getPassword());
        }

        // 更新用户信息
        if (updateById(user)) {
            return Result.success("更新用户成功");
        }
        return Result.fail("更新用户失败");
    }

    @Override
    public Result deleteUser(Integer id) {
        if (removeById(id)) {
            return Result.success("删除用户成功");
        }
        return Result.fail("删除用户失败");
    }

    @Override
    public Result batchDeleteUsers(List<Integer> ids) {
        if (removeBatchByIds(ids)) {
            return Result.success("批量删除成功");
        }
        return Result.fail("批量删除失败");
    }


    @Override
    public Result register(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        if (count(queryWrapper) > 0) {
            return Result.fail("用户名已存在");
        }

        user.setPassword(passwordEncoder.encode(user.getPassword()));

        user.setRole(2);

        if (save(user)) {
            return Result.success("注册成功");
        }
        return Result.fail("注册失败");
    }

    @Override
    public Result getUserById(Integer id) {
        User user = getById(id);
        if (user != null) {
            user.setPassword(null);
            return Result.success(user);
        }
        return Result.fail("用户不存在");
    }
}